// https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
const request = require('request')
// var NodeCache = require('node-cache') ;
var getAccessToken = require('./getWxaccesstoken');
var wxconfig = require('../appConfig').wxconfig;
var wxInfoUrl = wxconfig.wxInfoUrl;
// var myCache = new NodeCache({  stdTTL :3600 ,  checkperiod :3600 });

var getWxuserInfo = function(code) {
    return new Promise(function (resolve,reject) {
            getAccessToken(code).then((response) => {
                request.get({
                    uri: wxInfoUrl,
                    json: true,
                    qs: {
                        access_token: response.access_token,
                        openid:response.openid,
                        lang:'zh_CN'
                    }
                }, (err, res, body) => {
                    if (err) {
                        reject(err)
                    }
                    // err exp : {"errcode":40003,"errmsg":" invalid openid "}
                    if (body.errcode) {
                        reject(body.errcode + body.errmsg)
                    }
                    resolve(body)
                })
            })
    })
}
// 只要向外暴露一个获取值的方法就可以了
module.exports = getWxuserInfo
